package com.yn.iotxiao.controller;

import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.JWT.JWTUtil;
import com.yn.iotxiao.Utils.SecretUtil;
import com.yn.iotxiao.request.LoginUserPwd;
import com.yn.iotxiao.response.ErrorResult;
import com.yn.iotxiao.response.ResponseResult;
import com.yn.iotxiao.sql.entity.User.User;
import com.yn.iotxiao.sql.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/login")
@Slf4j
@RestController
@ResponseResult
public class LoginController {

    @Autowired
    UserService userService;

    @PostMapping
    public Object login(@Validated @RequestBody LoginUserPwd request) {
        String pwd = SecretUtil.md5(request.getPassword());
        if (pwd == null) {
            return new ErrorResult("获取密码失败");
        }
        User user = userService.getWithLoginId(request.getLoginId());
        if (user == null || user.getUid().isEmpty()) {
            return  new ErrorResult("用户名不存在");
        }
        if (!user.isCanLogin()) {
            return  new ErrorResult("不可登录");
        }
        if (!pwd.equals(user.getPassword())) {
            return new ErrorResult("密码错误");
        }

        String token = JWTUtil.createToken(user.getName(),user.getUid(), user.getPassword());

        JSONObject data = new JSONObject();
        data.put("token",token);
        data.put("name",user.getName());
        data.put("uid",user.getUid());
        data.put("type",user.getType());
        return  data;
    }


}
